<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Models\Bar;
use App\Models\Post;
use App\Services\PostService;
use App\Services\ReplyService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PostController extends Controller
{
    public function __construct(
        private PostService $postService,
        private ReplyService $replyService
    ) {}

    /**
     * 显示帖子列表（在贴吧详情页中）
     */
    public function index(Request $request, Bar $bar): Response
    {
        $sort = $request->input('sort', 'latest'); // latest, hot, essence
        // 优化：在服务层批量加载点赞和收藏状态，避免N+1查询
        $posts = $this->postService->getPostsList($bar, $sort, 15, $request->user());

        return Inertia::render('Bars/Show', [
            'bar' => $bar->load('owner'),
            'posts' => $posts,
            'filters' => [
                'sort' => $sort,
            ],
        ]);
    }

    /**
     * 显示发布帖子表单
     */
    public function create(Bar $bar): Response
    {
        return Inertia::render('Posts/Create', [
            'bar' => $bar,
        ]);
    }

    /**
     * 发布新帖子
     */
    public function store(StorePostRequest $request, Bar $bar): RedirectResponse
    {
        try {
            $post = $this->postService->createPost($bar, $request->user(), $request->validated());

            return redirect()
                ->route('posts.show', $post)
                ->with('success', '帖子发布成功！');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 显示帖子详情
     */
    public function show(Request $request, Post $post): Response
    {
        $post = $this->postService->getPostDetail($post);

        $isLiked = $request->user() ? $post->isLikedBy($request->user()) : false;
        $isFavorited = $request->user() ? $post->isFavoritedBy($request->user()) : false;

        // 获取回复列表
        $replies = $this->replyService->getRepliesList($post, $request->user());

        return Inertia::render('Posts/Show', [
            'post' => $post,
            'isLiked' => $isLiked,
            'isFavorited' => $isFavorited,
            'replies' => $replies,
        ]);
    }

    /**
     * 显示编辑帖子表单
     */
    public function edit(Post $post): Response
    {
        $this->authorize('update', $post);

        return Inertia::render('Posts/Edit', [
            'post' => $post->load('bar'),
        ]);
    }

    /**
     * 更新帖子
     */
    public function update(UpdatePostRequest $request, Post $post): RedirectResponse
    {
        try {
            $this->postService->updatePost($post, $request->user(), $request->validated());

            return redirect()
                ->route('posts.show', $post)
                ->with('success', '帖子更新成功！');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 删除帖子
     */
    public function destroy(Post $post): RedirectResponse
    {
        $this->authorize('delete', $post);

        try {
            $bar = $post->bar;
            $this->postService->deletePost($post, request()->user());

            return redirect()
                ->route('bars.show', $bar)
                ->with('success', '帖子已删除');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 点赞/取消点赞帖子
     */
    public function toggleLike(Request $request, Post $post): RedirectResponse
    {
        try {
            $isLiked = $this->postService->toggleLike($post, $request->user());

            return back()->with('success', $isLiked ? '已点赞' : '已取消点赞');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 收藏/取消收藏帖子
     */
    public function toggleFavorite(Request $request, Post $post): RedirectResponse
    {
        try {
            $isFavorited = $this->postService->toggleFavorite($post, $request->user());

            return back()->with('success', $isFavorited ? '已收藏' : '已取消收藏');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 置顶/取消置顶（仅吧主可操作）
     */
    public function togglePin(Request $request, Post $post): RedirectResponse
    {
        try {
            $isPinned = $this->postService->togglePin($post, $request->user());

            return back()->with('success', $isPinned ? '已置顶' : '已取消置顶');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 加精/取消精华（仅吧主可操作）
     */
    public function toggleEssence(Request $request, Post $post): RedirectResponse
    {
        try {
            $isEssence = $this->postService->toggleEssence($post, $request->user());

            return back()->with('success', $isEssence ? '已设为精华' : '已取消精华');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
